# Copyright (C) 2007 "dbsolution sas" 
#
# This file is part of Weebotee.
#
# Weebotee is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Weebotee is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Weebotee.  If not, see <http://www.gnu.org/licenses/>.

from django.template import Library
from apps.core.models.billing import Billing
from apps.core.models.section import Section
from apps.core.backend.views.forms.paymethod_form import PaymethodForm
from django.http import HttpResponseRedirect, Http404
from django.shortcuts import render_to_response
from ..libs.decorators import wizcleaner
register = Library()

def listBillings(request):
    biList = Billing.objects.filter(user=request.user)
    section = Section.objects.get(slug="billing")
    default_context = {
        'section':section,
        'content':biList,
        'user':request.user
    }
    return render_to_response("fe_listbillings.html", default_context)

@wizcleaner
def billings(request, identifier=None):
    # controllo wizard
    isWizard = False
    if "wiz" in request.session.keys():
        isWizard = True
    section = Section.objects.filter(viewtype__iexact="core:Billing")[0]
    initial = {"user" : request.user.username }
    try:
        bil = Billing.objects.get(id=identifier)
        initial.update(bil.__dict__)
    except:
        pass
    if request.method == "POST":
        form = PaymethodForm(request.POST, initial=initial)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect("/"+section.slug)
    else:
        form = PaymethodForm(initial=initial)
        
    default_context = {
        'section':section,
        'form': form,
        'user':request.user,
        'isWizard':isWizard
    }
    return render_to_response("fe_billings.html", default_context)
